package com.app.controller;


import com.app.aspect.AutoLog;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.IFwService;
import com.app.service.Impl.SysDicServiceImpl;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 房屋 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-02-27
 */
@Api(tags = "房屋模块")
@RestController
@RequestMapping("/fw")
public class FwController {

    @Autowired
    private FwMapper fwMapper;

    @Autowired
    private IFwService fwService;

    @Autowired
    private YonghuMapper yonghuMapper;

    @Autowired
    private SysDicServiceImpl SysDicService;

    @Autowired
    private FwSecurityDepositConfigMapper fwSecurityDepositConfigMapper;

    @Autowired
    private FwjzMapper fwjzMapper;

    @Autowired
    private FwPropertyFeeConfigMapper fwPropertyFeeConfigMapper;

    @Autowired
    private PropertyFeeLogMapper propertyFeeLogMapper;

    @Autowired
    private TenantRelationshipMapper tenantRelationshipMapper;

    @Autowired
    private FwbhMapper fwbhMapper;


    @ApiOperation(value = "小程序---根据用户名和身份证号查询房屋信息", notes = "小程序---根据用户名和身份证号查询房屋信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "leaseCertificateNumber", value = "租赁编号", required = true, dataType = "String")
    })

    @GetMapping("/applet/queryFwInfoByUserNameAndIdCard")
    public Result appletQueryFwInfoByUserNameAndIdCard(String userName, String idCard,String leaseCertificateNumber) {


        List<Fw> list = fwMapper.getLoginUserFws(userName, idCard, leaseCertificateNumber);

        QueryWrapper<SysDic> sysDicQueryWrapper = new QueryWrapper<>();
        sysDicQueryWrapper.eq("type", "yydh");
        SysDic sysDic = SysDicService.getOne(sysDicQueryWrapper);
        JSONObject result = new JSONObject();
        result.put("list", list);
        result.put("yydh", sysDic.getValue());
        return Result.success(result);
    }


    @ApiOperation(value = "管理后台-房屋基本信息管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseType", value = "房屋类型", required = false, dataType = "String"),
            @ApiImplicitParam(name = "houseStatus", value = "房屋状态", required = false, dataType = "String"),
            @ApiImplicitParam(name = "houseKeyword", value = "房屋关键词", required = false, dataType = "String"),
            @ApiImplicitParam(name = "lesseeKeyword", value = "承租人关键词", required = false, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "条", required = true, dataType = "Integer"),
    })
    @GetMapping("/admin/getHousingInformation")
    public Result getHousingInformation(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                        String houseType, String houseStatus, String houseKeyword, String lesseeKeyword,String uniqueId) {
        Page<Fw> fwPage = new Page<>(page, limit);
//        return Result.success(this.fwService.adminPage(fwPage, houseType, houseStatus, houseKeyword, lesseeKeyword));
        IPage<Fw> iPage = fwMapper.adminGetFwInfoList(fwPage, houseType, houseStatus, houseKeyword, lesseeKeyword,uniqueId);
        return Result.success(iPage);
    }


    @ApiOperation(value = "管理后台---房屋详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "房屋id", required = true, dataType = "Integer")
    })
    @GetMapping("/admin/adminGetFwInfoById")
    public Result adminGetFwInfoById(Integer id){
        Fw fw = fwMapper.adminGetFwInfoById(id);

        if (fw != null && fw.getHouseType()!= null){
            QueryWrapper<Fwlx> fwlxQueryWrapper = new QueryWrapper<>();
            fwlxQueryWrapper.eq("house_type_name", fw.getHouseType());
            Fwlx fwlx = fwlxMapper.selectOne(fwlxQueryWrapper);
            //应交标准
            fw.setYingjiaobiaozhun(fw.getUnitPricePerSquare());
            //调节因素
            fw.setTiaojieyinsu(fw.getHjxs());
            //实收标准
            fw.setShishoubiaozhun(fw.getCalculatedPrice());
            //合计月租
            fw.setHejiyuezu(fw.getTotalPrice());
        }

        return Result.success(fw);
    }


    @ApiOperation(value = "管理后台---生成租赁证编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseType", value = "房屋类型", required = true, dataType = "String")
    })
    @GetMapping("/admin/generateLeaseCertificateNumberNew")
    public Result generateLeaseCertificateNumberNew(String houseType){
        if(houseType == null || houseType.equals("")){
            return Result.error("房屋类型不能为空");
        }
        JSONObject result = new JSONObject();
        String generate_leaseCertificateNumber = "";
        String generate_leaseCertificateNumber_New = "";
        QueryWrapper<Fw> queryWrapper = new QueryWrapper<>();
        if (houseType.equals("廉租房") || houseType.equals("直管公房") || houseType.equals("公租房")){
            queryWrapper.eq("house_type", houseType);
            queryWrapper.orderByDesc("lease_certificate_number");
            queryWrapper.last("limit 1");
            Fw fw = fwMapper.selectOne(queryWrapper);
            generate_leaseCertificateNumber = fw.getLeaseCertificateNumber() + 1;
            if (houseType.equals("廉租房")){
                generate_leaseCertificateNumber_New = "L" + generate_leaseCertificateNumber;
            }else if (houseType.equals("直管公房")){
                generate_leaseCertificateNumber_New = "Z" + generate_leaseCertificateNumber;
            }else if (houseType.equals("公租房")){
                generate_leaseCertificateNumber_New = "G" + generate_leaseCertificateNumber;
            }
        }
        result.put("leaseCertificateNumber", generate_leaseCertificateNumber);
        result.put("leaseCertificateNumberNew", generate_leaseCertificateNumber_New);
        return Result.success(result);
    }

    /**
     * 新增或编辑房屋
     *
     * @param fw 房屋对象
     * @return 操作结果
     */
//    @ApiOperation(value = "新增或编辑房屋")
//    @AutoLog("新增或编辑房屋")
//    @PostMapping("/admin/saveOrUpdate")
//    public Result saveOrUpdate(@RequestBody Fw fw) {
//        try {
//            // 输入验证
//            if (fw == null) {
//                return Result.error("房屋对象无效");
//            }
//
//            boolean savedOrUpdated;
//            if (fw.getId() != null) {
//                savedOrUpdated = this.fwService.updateById(fw);
//            } else {
//                savedOrUpdated = this.fwService.save(fw);
//            }
//
//            if (savedOrUpdated) {
//                return Result.success("房屋保存或更新成功");
//            } else {
//                return Result.error("房屋保存或更新失败");
//            }
//        } catch (Exception e) {
//            return Result.error("系统错误，请稍后再试");
//        }
//    }

    @Autowired
    private FwlxMapper fwlxMapper;
    @Autowired
    private FwlqMapper fwlqMapper;
    @Autowired
    private FwLcwhMapper fwLcwhMapper;

    @ApiOperation(value = "管理后台---计算房屋租金")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseType", value = "房屋类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "usableArea", value = "面积", required = true, dataType = "String"),
            @ApiImplicitParam(name = "houseAreaType", value = "类区", required = true, dataType = "String"),
            @ApiImplicitParam(name = "floorLevel", value = "楼层", required = true, dataType = "String")
    })
    @GetMapping("/admin/calculateHousingRent")
    public Result calculateHousingRent(String houseType,String usableArea,String houseAreaType,String floorLevel){
        JSONObject result = new JSONObject();

        QueryWrapper<Fwlx> fwlxQueryWrapper = new QueryWrapper<>();
        fwlxQueryWrapper.eq("house_type_name", houseType);
        Fwlx fwlx = fwlxMapper.selectOne(fwlxQueryWrapper);
        BigDecimal unitPricePerSquare = fwlx.getUnitPricePerSquare();
        //应交标准
        result.put("yingjiaobiaozhun",fwlx.getUnitPricePerSquare());
        //调节因素
        ///类区
        QueryWrapper<Fwlq> fwlqQueryWrapper = new QueryWrapper<>();
        fwlqQueryWrapper.eq("lq_value", houseAreaType);
        Fwlq fwlq = fwlqMapper.selectOne(fwlqQueryWrapper);
        BigDecimal lq_xs = fwlq.getXsValue().divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);

        ///楼层
        QueryWrapper<FwLcwh> fwLcwhQueryWrapper = new QueryWrapper<>();
        fwLcwhQueryWrapper.eq("lc_value", floorLevel);
        FwLcwh fwLcwh = fwLcwhMapper.selectOne(fwLcwhQueryWrapper);
        BigDecimal lc_xs = fwLcwh.getXsValue().divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);;

        result.put("tiaojieyinsu",lq_xs.add(lc_xs));

        //实收标准 = 房屋类型的标准 * （1 + 类区 + 楼层）
        BigDecimal totalPrice = unitPricePerSquare.multiply(new BigDecimal("1").add(lq_xs).add(lc_xs));
        result.put("shishoubiaozhun",totalPrice);
        //合计月租 = 房屋面积 usableArea * 房屋类型的单价 totalPrice
        BigDecimal totalPriceDouble = totalPrice.multiply(new BigDecimal(usableArea)).setScale(2,BigDecimal.ROUND_HALF_UP);
        result.put("hejiyuezu",totalPriceDouble);

        return Result.success(result);
    }


    @ApiOperation(value = "新增或编辑房屋")
    @AutoLog("新增或编辑房屋")
    @PostMapping("/admin/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Fw fw) {

        //组装门牌号 = （building_number 或者 courtyard_number ）哪个有值用哪个 + unit_number + floor_level + "0" + room_number
        String building_number = fw.getBuildingNumber();
        String courtyard_number = fw.getCourtyardNumber();
        String unit_number = fw.getUnitNumber();
        String floor_level = fw.getFloorLevel();
        String room_number = fw.getRoomNumber();

        String mph = "";
        if (building_number !=null &&!building_number.equals("")){
            if (Integer.valueOf(room_number)<=9){
                mph = building_number +"-"+ unit_number +"-"+ floor_level + "0" + room_number;
            }else {
                mph = building_number +"-"+ unit_number +"-"+ floor_level + room_number;
            }
        }else if (courtyard_number !=null &&!courtyard_number.equals("")){
            mph = courtyard_number +"-"+ unit_number +"-"+ floor_level + "0" + room_number;
        }
        fw.setMphValue(mph);

        //组装房屋地址
        String address_value = "";
        if (building_number !=null &&!building_number.equals("")){
            address_value = building_number + "号楼" + unit_number + "单元" + floor_level + "层" + room_number + "室";
        }else {
            address_value = courtyard_number + "号院" + unit_number + "单元" + floor_level + "层" + room_number + "室";
        }
        fw.setAddressValue(address_value);

        if (fw.getId() == null){

            //生成唯一标识id
            String unique_id = generateStringFromTimestamp();

            if ("直管公房".equals(fw.getHouseType()) && !fw.getLeaseCertificateNumberNew().startsWith("Z")){
                return Result.error("直管公房的租赁证号必须以Z开头!");
            }else if ("廉租房".equals(fw.getHouseType()) && !fw.getLeaseCertificateNumberNew().startsWith("L")){
                return Result.error("廉租房的租赁证号必须以L开头!");
            }else if ("公租房".equals(fw.getHouseType()) && !fw.getLeaseCertificateNumberNew().startsWith("G")){
                return Result.error("公租房的租赁证号必须以G开头!");
            }



            fw.setIdValue(unique_id);
            fwMapper.insert(fw);

            Fwbh fwbh = new Fwbh();
            fwbh.setUniqueId(unique_id);
            fwbh.setDataId(fw.getId());
            fwbh.setTimeStamp(LocalDateTime.now());
            fwbh.setReasonText("新建房屋");
            fwbh.setAddressValue(address_value);
            fwbh.setAreaName(fw.getAreaName());
            fwbh.setStructureType(fw.getStructureType());
            fwbh.setHouseType(fw.getHouseType());
            fwbh.setBuildingArea(fw.getBuildingArea());
            fwbh.setUsableArea(fw.getUsableArea());
            fwbh.setMonthlyRent(fw.getTotalMonthlyRent());
            fwbhMapper.insert(fwbh);

        }else {

            fwMapper.updateById(fw);

        }
        return Result.success("操作成功！");
    }


    public static String generateStringFromTimestamp() {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();
        // 将时间戳转换为字符串
        String timestampStr = String.valueOf(timestamp);
        // 定义最终字符串的长度
        int targetLength = 21;
        StringBuilder result = new StringBuilder();

        // 取时间戳的一部分
        if (timestampStr.length() > 10) {
            result.append(timestampStr.substring(timestampStr.length() - 10));
        } else {
            result.append(timestampStr);
        }

        // 不足长度的部分用 0 补齐
        while (result.length() < targetLength) {
            result.insert(0, "0");
        }

        return result.toString();
    }

    /**
     * 删除房屋
     *
     * @param id 房屋ID
     * @return 操作结果
     */
    @ApiOperation(value = "删除房屋")
    @GetMapping("/delete")
    public Result delete(Integer id) {
        try {
            // 获取房屋
            Fw fw = this.fwService.getById(id);
            if (fw == null) {
                return Result.error("该房屋不存在");
            }

            // 设置删除标志并更新
            fw.setIsDel(1);
            boolean updateSuccess = this.fwService.updateById(fw);

            if (updateSuccess) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败，请稍后再试");
            }
        } catch (Exception e) {
            return Result.error("系统错误，请稍后再试");
        }
    }

    //小程序 ---- 计算所选房屋的 保证金 / 房租 / 滞纳金 / 物业费  是否欠费
    @ApiOperation(value = "小程序-计算所选房屋的 保证金 / 房租 / 滞纳金 / 物业费  是否欠费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "房屋主键id", required = true, dataType = "Integer")
    })
    @GetMapping("/applet/getFwInfoById")
    public Result getFwInfoById(Integer id) {
        Fw fw = fwMapper.getFwInfoById(id);

        Boolean whetherThereIsArrearage = false;//所有事项是否欠费


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<Map<String, Object>> list = new ArrayList<>();

        //检查保证⾦缴纳
        //查询这个房屋的最新的承租人，有没有缴纳
        QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
        tenantRelationshipQueryWrapper.eq("unique_id", fw.getIdValue());
        tenantRelationshipQueryWrapper.orderByDesc("tenant_serial_number");
        tenantRelationshipQueryWrapper.last("limit 1");
        TenantRelationship tenantRelationship = tenantRelationshipMapper.selectOne(tenantRelationshipQueryWrapper);
        if (tenantRelationship !=null){
            BigDecimal new_deposit = tenantRelationship.getNewDeposit();
            BigDecimal new_deposit_returned = tenantRelationship.getNewDepositReturned();
            //如果没有新的保证金缴纳  或者  交了新的保证金 但是已经退费了，就需要重新缴纳
            if (new_deposit ==null || (new_deposit_returned != null && new_deposit_returned.compareTo(BigDecimal.ZERO) > 0)  ){

                //查询当前房屋类型的缴费标准
                QueryWrapper<FwSecurityDepositConfig> fwSecurityDepositConfigQueryWrapper = new QueryWrapper<>();
                fwSecurityDepositConfigQueryWrapper.eq("house_type", fw.getHouseType());
                fwSecurityDepositConfigQueryWrapper.last("limit 1");
                FwSecurityDepositConfig config = fwSecurityDepositConfigMapper.selectOne(fwSecurityDepositConfigQueryWrapper);
                if (config !=null){
                    BigDecimal charging_standard = config.getChargingStandard();
                    fw.setNeedDepositPaid(charging_standard);
                }

                QueryWrapper<FwSecurityDepositConfig> securityDepositConfigQueryWrapper = new QueryWrapper<>();
                securityDepositConfigQueryWrapper.orderByAsc("id");
                List<FwSecurityDepositConfig> securityDepositConfigs = fwSecurityDepositConfigMapper.selectList(securityDepositConfigQueryWrapper);
                fw.setFwSecurityDepositConfigList(securityDepositConfigs);
            }
            whetherThereIsArrearage = true;
        }

        Boolean isArrearage = false;//是否欠费
        LocalDateTime arrearageStartDate = null;
        BigDecimal arrearageRentToBePaid = null;
        //检查房租⽋费
        //查询 缴纳时间 <当前时间 < 至缴纳时间  内有没有缴费记录
        List<Fwjz> jzLogs = fwjzMapper.selectCurrentLogByUniqueId(fw.getIdValue());
        if (jzLogs.isEmpty()){//没有提前的缴费记录，重新拿用户历史缴费记录的第一条
            QueryWrapper<Fwjz> fwjzQueryWrapper = new QueryWrapper<>();
            fwjzQueryWrapper.eq("unique_id",fw.getIdValue());
            fwjzQueryWrapper.orderByDesc("until_pay_time");
            fwjzQueryWrapper.last("limit 1");
            Fwjz newJzlog = fwjzMapper.selectOne(fwjzQueryWrapper);
            if (newJzlog !=null){
                isArrearage = true;
                // 拿出最后的至缴纳时间
                LocalDateTime untilPayTime = newJzlog.getUntilPayTime();
                arrearageStartDate = untilPayTime;
                // 将 LocalDateTime 转换为 LocalDate，取日期部分
                LocalDate untilPayDate = untilPayTime.toLocalDate();
                // 获取当前日期
                LocalDate nextMonthFirstDay = LocalDate.now();
                // 计算当前月的下一个月的 1 号
//                LocalDate nextMonthFirstDay = currentDate.withDayOfMonth(1).plusMonths(1);
                // 计算 untilPayDate 到 nextMonthFirstDay 之间的月数
                long monthsBetween = ChronoUnit.MONTHS.between(YearMonth.from(untilPayDate), YearMonth.from(nextMonthFirstDay));
                //计算月租
                Double totalPrice = fw.getTotalPrice();
                //需要缴纳的房租 = 月份 * 月租
                // setScale(2, BigDecimal.ROUND_HALF_UP) 方法设置结果保留两位小数，并进行四舍五入
                BigDecimal rentToBePaid = new BigDecimal(monthsBetween).multiply(new BigDecimal(totalPrice)).setScale(2,BigDecimal.ROUND_HALF_UP);
                arrearageRentToBePaid = rentToBePaid;

                //计算应交的房租
                Double payableTotalPrice = fw.getPayableTotalPrice();
                //需要缴纳的房租 = 月份 * 月租
                // setScale(2, BigDecimal.ROUND_HALF_UP) 方法设置结果保留两位小数，并进行四舍五入
                BigDecimal rentToBePaid2 = new BigDecimal(monthsBetween).multiply(new BigDecimal(payableTotalPrice)).setScale(2,BigDecimal.ROUND_HALF_UP);


                //赋值欠费天数
                Integer rentLateDays = (int) ChronoUnit.DAYS.between(untilPayTime, nextMonthFirstDay.atStartOfDay());
                fw.setRentLateDays(rentLateDays);
                fw.setRentToBePaidStartTime(untilPayTime);
                fw.setRentToBePaidEndTime(nextMonthFirstDay.atStartOfDay());
                fw.setLateFeeStartTime(untilPayTime);
                fw.setLateFeeEndTime(nextMonthFirstDay.atStartOfDay());
                fw.setRentToBePaid(rentToBePaid);

                Map<String, Object> map = new HashMap<>();
                map.put("name", "房租⽋费");
                map.put("startTime", formatter.format(untilPayTime));
                map.put("endTime", formatter.format(nextMonthFirstDay.atStartOfDay()));
                map.put("amount", rentToBePaid);
                map.put("payableTotalPrice", rentToBePaid2);

                map.put("monthsBetween", monthsBetween);

                map.put("daysBetween", rentLateDays);
                list.add(map);

            }else {//没有历史缴费记录，取房屋的居住时间
                isArrearage = true;
                LocalDateTime liveTime =fw.getLatestLeaseRelationshipTime();
                arrearageStartDate = liveTime;
                // 获取当前日期
                LocalDate nextMonthFirstDay = LocalDate.now();
                // 计算当前月的下一个月的 1 号
//                LocalDate nextMonthFirstDay = currentDate.withDayOfMonth(1).plusMonths(1);
                // 计算 liveTime 到 nextMonthFirstDay 之间的月数
                long monthsBetween = ChronoUnit.MONTHS.between(liveTime.toLocalDate(), nextMonthFirstDay);
                //计算月租
                Double totalPrice = fw.getTotalPrice();
                //需要缴纳的房租 = 月份 * 月租
                // setScale(2, BigDecimal.ROUND_HALF_UP) 方法设置结果保留两位小数，并进行四舍五入
                BigDecimal rentToBePaid = new BigDecimal(monthsBetween).multiply(new BigDecimal(totalPrice)).setScale(2,BigDecimal.ROUND_HALF_UP);
                arrearageRentToBePaid = rentToBePaid;

                //计算应交的房租
                Double payableTotalPrice = fw.getPayableTotalPrice();
                //需要缴纳的房租 = 月份 * 月租
                // setScale(2, BigDecimal.ROUND_HALF_UP) 方法设置结果保留两位小数，并进行四舍五入
                BigDecimal rentToBePaid2 = new BigDecimal(monthsBetween).multiply(new BigDecimal(payableTotalPrice)).setScale(2,BigDecimal.ROUND_HALF_UP);

                fw.setRentToBePaidStartTime(liveTime);
                fw.setRentToBePaidEndTime(nextMonthFirstDay.atStartOfDay());
                fw.setRentToBePaid(rentToBePaid);
                fw.setLateFeeStartTime(liveTime);
                fw.setLateFeeEndTime(nextMonthFirstDay.atStartOfDay());

                Map<String, Object> map = new HashMap<>();
                map.put("name", "房租⽋费");
                map.put("startTime", formatter.format(liveTime));
                map.put("endTime", formatter.format(nextMonthFirstDay.atStartOfDay()));


                map.put("amount", rentToBePaid);
                map.put("amount", rentToBePaid);
                map.put("payableTotalPrice", rentToBePaid2);

                //赋值欠费天数
                Integer rentLateDays = (int) ChronoUnit.DAYS.between(liveTime, nextMonthFirstDay.atStartOfDay());
                map.put("daysBetween", rentLateDays);
                list.add(map);
            }

            whetherThereIsArrearage = true;
        }
        //检查滞纳⾦
        if (isArrearage){
            //计算滞纳天数
            long daysBetween = ChronoUnit.DAYS.between(arrearageStartDate, LocalDateTime.now());
//            //滞纳金 = 欠费天数daysBetween * 欠费金额arrearageRentToBePaid * 0.005
//            BigDecimal arrearageAmount = new BigDecimal(daysBetween).multiply(arrearageRentToBePaid).multiply(new BigDecimal("0.005")).setScale(2,BigDecimal.ROUND_HALF_UP);
//            //滞纳⾦原则上不超过⽋费⾦额
//            if (arrearageAmount.compareTo(arrearageRentToBePaid) > 0){
//                arrearageAmount = fw.getNeedDepositPaid();
//            }
//            fw.setArrearageRentToBePaid(arrearageRentToBePaid);
//            fw.setLateDays(daysBetween);
//            fw.setLateFee(arrearageAmount);


            //新逻辑
            //去年的一年没交，收取年租金的10%
            //本年的1月-3月（不算滞纳金）
            //其他时间，计算公式是 欠费天数 * 日租金 * 0.005
            BigDecimal totalArrearageAmount = new BigDecimal(0);

            //1，先判断arrearageStartDate时间，是否是去年的
            if (arrearageStartDate.getYear() == LocalDateTime.now().getYear()-1){
                //去年欠了多少天，只判断到去年年底的天数
                LocalDateTime lastYearEnd = LocalDateTime.of(arrearageStartDate.getYear(),12,31,23,59,59);
                long oldDaysBetween = ChronoUnit.DAYS.between(arrearageStartDate, lastYearEnd);
                //计算去年的欠费 = (月租金 / 30) * 去年欠了多少天 * 0.1
                BigDecimal oldArrearageAmount = new BigDecimal(fw.getTotalPrice()).divide(new BigDecimal("30"),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(oldDaysBetween)).multiply(new BigDecimal("0.1")).setScale(2,BigDecimal.ROUND_HALF_UP);
                totalArrearageAmount = totalArrearageAmount.add(oldArrearageAmount);
            }


            //2，判断是否是在本年的1月-3月
            //如果不是，则需要再计算滞纳金
            if (arrearageStartDate.getYear() == LocalDateTime.now().getYear() && arrearageStartDate.getMonthValue() >= 4) {
                //今年开始的第一天 到  上个月最后一天的天数
                LocalDateTime yearStart = LocalDateTime.of(arrearageStartDate.getYear(),1,1,0,0,0);
                LocalDateTime lastMonthEnd = LocalDateTime.of(arrearageStartDate.getYear(),arrearageStartDate.getMonthValue(),arrearageStartDate.getDayOfMonth(),23,59,59);
                long newDaysBetween = ChronoUnit.DAYS.between(yearStart, lastMonthEnd);
                //计算本年的欠费 =  本年欠费天数 * 日租金 * 0.005
                BigDecimal newArrearageAmount = new BigDecimal(fw.getTotalPrice()).multiply(new BigDecimal(newDaysBetween)).multiply(new BigDecimal("0.005")).setScale(2,BigDecimal.ROUND_HALF_UP);
                totalArrearageAmount = totalArrearageAmount.add(newArrearageAmount);
            }

            fw.setArrearageRentToBePaid(arrearageRentToBePaid);
            fw.setLateDays(daysBetween);
            fw.setLateFee(totalArrearageAmount);

            whetherThereIsArrearage = true;

            Map<String, Object> map = new HashMap<>();
            map.put("name", "滞纳金");
            map.put("startTime", formatter.format(fw.getLateFeeStartTime()));
            map.put("endTime", formatter.format(fw.getLateFeeEndTime()));
            map.put("amount", totalArrearageAmount);
            map.put("payableTotalPrice", totalArrearageAmount);
            map.put("newDaysBetween", daysBetween);
            list.add(map);
        }
        //物业费⽋费
        //查询每平米收费标准
        QueryWrapper<FwPropertyFeeConfig> fwPropertyFeeConfigQueryWrapper = new QueryWrapper<>();
        FwPropertyFeeConfig fwPropertyFeeConfig = fwPropertyFeeConfigMapper.selectOne(fwPropertyFeeConfigQueryWrapper);
        //查询 缴纳时间 <当前时间 < 至缴纳时间  内有没有缴费记录
        List<PropertyFeeLog> selectByPropertyId = propertyFeeLogMapper.selectByPropertyId(fw.getIdValue());

        Long monthsBetween = null;
        if (selectByPropertyId.isEmpty()){
            QueryWrapper<PropertyFeeLog> propertyFeeLogQueryWrapper = new QueryWrapper<>();
            propertyFeeLogQueryWrapper.eq("id_value",fw.getIdValue());
            propertyFeeLogQueryWrapper.orderByDesc("payment_end");
            propertyFeeLogQueryWrapper.last("limit 1");
            PropertyFeeLog propertyFeeLog = propertyFeeLogMapper.selectOne(propertyFeeLogQueryWrapper);
            if (propertyFeeLog !=null){
                // 拿出最后的至缴纳时间
                LocalDateTime untilPayTime = propertyFeeLog.getPaymentEnd();
                // 将 LocalDateTime 转换为 LocalDate，取日期部分
                LocalDate untilPayDate = untilPayTime.toLocalDate();
                // 获取当前日期
                LocalDate nextMonthFirstDay = LocalDate.now();
                // 计算当前月的下一个月的 1 号
//                LocalDate nextMonthFirstDay = currentDate.withDayOfMonth(1).plusMonths(1);
                // 计算 untilPayDate 到 nextMonthFirstDay 之间的月数
                monthsBetween = ChronoUnit.MONTHS.between(YearMonth.from(untilPayDate), YearMonth.from(nextMonthFirstDay));
                //建筑面积
                Double buildingArea = fw.getBuildingArea();
                //查询每平米收费标准
                BigDecimal propertyFeeStandard = fwPropertyFeeConfig.getChargingStandard();
                //计算需要缴纳的物业费 = 建筑⾯积x收费标准x⽋费⽉份
                BigDecimal propertyFeePaid = new BigDecimal(buildingArea).multiply(propertyFeeStandard).multiply(new BigDecimal(monthsBetween)).setScale(2,BigDecimal.ROUND_HALF_UP);

                fw.setNeedPropertyFeeMonthsBetween(monthsBetween);
                fw.setNeedPropertyFeeStartTime(untilPayTime);
                fw.setNeedPropertyFeeEndTime(nextMonthFirstDay.atStartOfDay());
                fw.setPropertyFeeStandard(propertyFeeStandard);
                fw.setNeedPropertyFee(propertyFeePaid);

            }else {
                //没有历史缴费记录，取房屋的居住时间
                LocalDateTime liveTime =fw.getLatestLeaseRelationshipTime();
                // 获取当前日期
                LocalDate nextMonthFirstDay = LocalDate.now();
                // 计算当前月的下一个月的 1 号
//                LocalDate nextMonthFirstDay = currentDate.withDayOfMonth(1).plusMonths(1);
                // 计算 liveTime 到 nextMonthFirstDay 之间的月数
                monthsBetween = ChronoUnit.MONTHS.between(liveTime.toLocalDate(), nextMonthFirstDay);
                //建筑面积
                Double buildingArea = fw.getBuildingArea();
                //查询每平米收费标准
                BigDecimal propertyFeeStandard = fwPropertyFeeConfig.getChargingStandard();
                //计算需要缴纳的物业费 = 建筑⾯积x收费标准x⽋费⽉份
                BigDecimal propertyFeePaid = new BigDecimal(buildingArea).multiply(propertyFeeStandard).multiply(new BigDecimal(monthsBetween)).setScale(2,BigDecimal.ROUND_HALF_UP);

                fw.setNeedPropertyFeeMonthsBetween(monthsBetween);
                fw.setNeedPropertyFeeStartTime(liveTime);
                fw.setNeedPropertyFeeEndTime(nextMonthFirstDay.atStartOfDay());
                fw.setPropertyFeeStandard(propertyFeeStandard);
                fw.setNeedPropertyFee(propertyFeePaid);
            }
            whetherThereIsArrearage = true;

            Map<String, Object> map = new HashMap<>();
            map.put("name", "物业费⽋费");
            map.put("startTime", formatter.format(fw.getNeedPropertyFeeStartTime()));
            map.put("endTime", formatter.format(fw.getNeedPropertyFeeEndTime()));
            map.put("amount", fw.getNeedPropertyFee());
            map.put("payableTotalPrice", fw.getNeedPropertyFee());
            map.put("monthsBetween",monthsBetween);
            list.add(map);
        }

        fw.setArrearsFeesList(list);

        //没有欠费，则需要列出缴费时段
        if (whetherThereIsArrearage){

            //房租------------------------
            //计算半年的房租 = 月租金 * 6
            BigDecimal halfYearRent = new BigDecimal(fw.getTotalPrice()).multiply(new BigDecimal("6")).setScale(2,BigDecimal.ROUND_HALF_UP);
            //计算一年的房租 = 月租金 * 12
            BigDecimal yearRent = new BigDecimal(fw.getTotalPrice()).multiply(new BigDecimal("12")).setScale(2,BigDecimal.ROUND_HALF_UP);
            //计算一个季度的房租 = 月租金 * 3
            BigDecimal quarterRent = new BigDecimal(fw.getTotalPrice()).multiply(new BigDecimal("3")).setScale(2,BigDecimal.ROUND_HALF_UP);

            //应交半年的房租
            BigDecimal payableTotalPrice_6 = new BigDecimal(fw.getPayableTotalPrice()).multiply(new BigDecimal("6")).setScale(2,BigDecimal.ROUND_HALF_UP);
            //应交一年的房租
            BigDecimal payableTotalPrice_12 = new BigDecimal(fw.getPayableTotalPrice()).multiply(new BigDecimal("12")).setScale(2,BigDecimal.ROUND_HALF_UP);
            //应交一个季度的房租
            BigDecimal payableTotalPrice_3 = new BigDecimal(fw.getPayableTotalPrice()).multiply(new BigDecimal("3")).setScale(2,BigDecimal.ROUND_HALF_UP);

            //列出选择项
            List<Map<String, Object>> timePeriods = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("id",1);
            map1.put("timePeriod","上半年");
            map1.put("rentMonth",6);
            map1.put("amount",halfYearRent);
            map1.put("payableTotalPrice",payableTotalPrice_6);
            map1.put("endTime",fw.getExpirationDate().plusMonths(6).withDayOfMonth(1));
            timePeriods.add(map1);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("id",2);
            map2.put("timePeriod","下半年");
            map2.put("rentMonth",6);
            map2.put("amount",halfYearRent);
            map2.put("payableTotalPrice",payableTotalPrice_6);
            map2.put("endTime",fw.getExpirationDate().plusMonths(6).withDayOfMonth(1));
            timePeriods.add(map2);
            Map<String, Object> map3 = new HashMap<>();
            map3.put("id",3);
            map3.put("timePeriod","一年");
            map3.put("rentMonth",12);
            map3.put("amount",yearRent);
            map3.put("payableTotalPrice",payableTotalPrice_12);
            map3.put("endTime",fw.getExpirationDate().plusMonths(12).withDayOfMonth(1));
            timePeriods.add(map3);
            fw.setTimePeriods(timePeriods);
            //列出更多时段
            List<Map<String, Object>> moreTimePeriods = new ArrayList<>();
            Map<String, Object> map4 = new HashMap<>();
            map4.put("id",1);
            map4.put("timePeriod","1-3⽉");
            map4.put("rentMonth",3);
            map4.put("amount",quarterRent);
            map4.put("payableTotalPrice",payableTotalPrice_3);
            map4.put("endTime",fw.getExpirationDate().plusMonths(3).withDayOfMonth(1));
            moreTimePeriods.add(map4);
            Map<String, Object> map5 = new HashMap<>();
            map5.put("id",2);
            map5.put("timePeriod","4-6⽉");
            map5.put("rentMonth",3);
            map5.put("amount",quarterRent);
            map5.put("payableTotalPrice",payableTotalPrice_3);
            map5.put("endTime",fw.getExpirationDate().plusMonths(3).withDayOfMonth(1));
            moreTimePeriods.add(map5);
            Map<String, Object> map6 = new HashMap<>();
            map6.put("id",3);
            map6.put("timePeriod","7-9⽉");
            map6.put("rentMonth",3);
            map6.put("amount",quarterRent);
            map6.put("payableTotalPrice",payableTotalPrice_3);
            map6.put("endTime",fw.getExpirationDate().plusMonths(3).withDayOfMonth(1));
            moreTimePeriods.add(map6);
            Map<String, Object> map7 = new HashMap<>();
            map7.put("id",4);
            map7.put("timePeriod","10-12⽉");
            map7.put("rentMonth",3);
            map7.put("amount",quarterRent);
            map7.put("payableTotalPrice",payableTotalPrice_3);
            map7.put("endTime",fw.getExpirationDate().plusMonths(3).withDayOfMonth(1));
            moreTimePeriods.add(map7);
            fw.setMoreTimePeriods(moreTimePeriods);


            //物业费------------------------
            //查询每平米收费标准
            BigDecimal propertyFeeStandard = fwPropertyFeeConfig.getChargingStandard();
            //计算需要缴纳的物业费 = 建筑⾯积x收费标准x12月
            BigDecimal  propertyFeePaid = new BigDecimal(fw.getBuildingArea()).multiply(propertyFeeStandard).multiply(new BigDecimal("12")).setScale(2,BigDecimal.ROUND_HALF_UP);

            //当前年度
            fw.setPropertyFee(propertyFeePaid);
            fw.setPropertyFeeTime(LocalDateTime.now().getYear());

            List<Map<String, Object>> propertyFeePeriods = new ArrayList<>();
            //下一年度
            Map<String, Object> map9 = new HashMap<>();
            map9.put("timePeriod",LocalDateTime.now().getYear()+1);
            map9.put("rentMonth",12);
            map9.put("amount",propertyFeePaid);
            propertyFeePeriods.add(map9);
            //下下年度
            Map<String, Object> map10 = new HashMap<>();
            map10.put("timePeriod",LocalDateTime.now().getYear()+2);
            map10.put("rentMonth",12);
            map10.put("amount",propertyFeePaid);
            propertyFeePeriods.add(map10);
            //下下下年度
            Map<String, Object> map11 = new HashMap<>();
            map11.put("timePeriod",LocalDateTime.now().getYear()+3);
            map11.put("rentMonth",12);
            map11.put("amount",propertyFeePaid);
            propertyFeePeriods.add(map11);
            fw.setPropertyFeePeriods(propertyFeePeriods);
        }

        return Result.success(fw);
    }




    @GetMapping("admin/queryFwOneStopOverview")
    public Result queryFwOneStopOverview(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                         @RequestParam(value = "limit", defaultValue = "10") Integer limit){


        return Result.success("");
    }



}

